package com.gitee.limaozhi.socket.lesson03.example3;

import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 服务器业务处理器
 *
 * @author hzlimaozhi
 * @date 2019/08/07 11:30
 */
public class ServerLogicHandler extends HandlerAdapter {

    private int prevReq = -1;
    private AtomicInteger req = new AtomicInteger(0);
    private boolean fireFinish = false;

    @Override
    public Handler handle(Object object) {
        context().execute(() -> {
            String request = (String) object;
            context().print(context().getName() + "：收到：" + request);

            String response;
            if (request.contains("你好")) {
                response = "你好";

            } else if (request.contains("天气")) {
                response = "晴天";

            } else if (request.contains("时间")) {
                response = new Date().toString();

            } else if (request.contains("温度")) {
                response = "36度";

            } else if (request.contains("拜拜")) {
                response = "拜拜";

            } else {
                response = "说人话";
            }

            // 发往下一个处理器
            next().handle(response);
            req.incrementAndGet();
            fireFinish();
//            context().print(context().getName() + "：ServerLogic：线程退出");
        });
        return this;
    }

    @Override
    public Handler finish(int prevReq) {
        this.prevReq = prevReq;
        fireFinish();
        return this;
    }

    private synchronized void fireFinish() {
        if (!fireFinish) {
            if (prevReq == req.get()) {
                fireFinish = true;
//                context().print(context().getName() + "：ServerLogic：" + req.get());
                next().finish(req.get());
            }
        }
    }

}
